package sticker.decompress.name;

import android.content.Context;
import android.content.SharedPreferences;
import sticker.decompress.IIdGenerator;

public class SharePrefIdGenerator implements IIdGenerator {

    static SharePrefIdGenerator sharePrefIdGenerator;
    static SharedPreferences sharedPreferences;
    static Context sharePrefContext;
    private static final String IdKey = "Key_Id";

    private SharePrefIdGenerator(Context context) {
        sharedPreferences = context.getSharedPreferences("SharePreferenceId", Context.MODE_PRIVATE);
    }

    public static void init(Context context) {
        sharePrefContext = context.getApplicationContext();
    }

    public static SharePrefIdGenerator getInstance() {

        if (sharePrefIdGenerator == null)
            synchronized (SharePrefIdGenerator.class) {
                if (sharePrefIdGenerator == null)
                    sharePrefIdGenerator = new SharePrefIdGenerator(sharePrefContext);
            }
        return sharePrefIdGenerator;
    }


    @Override
    public int getId() {

        if (sharePrefIdGenerator == null)
            throw new IllegalArgumentException("you should call init method first to " +
                    "init " + getClass().getSimpleName());

        int id = sharedPreferences.getInt(IdKey, 1);
        sharedPreferences.edit().putInt(IdKey, id + 1).apply();

        return id;
    }
}
